package com.hmall.order.time;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.common.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
public class TimeTask {

    @Autowired
    private ItemClient itemClient;

    //注入订单service
    @Autowired
    OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Scheduled(cron = "0 */1 * * * ?") // 每隔1分钟
    public void handleTast() {
        System.out.println("每隔1分钟执行一次 ==>" + LocalDateTime.now());
        Integer status = 1;
        //查询订单状态为一 的
        List<Order> orderList = orderService.list();

        Date date = new Date();
        long time = date.getTime();
        //遍历集合
        for (Order order : orderList) {
            long time1 = new Date().getTime() + 8 * 60 * 60 * 1000;
            long time2 = (time1 - time)/1000/60;
            if (time2 > 1) {
                //改变订单的状态值
                OrderDetail orderDetail = orderDetailService.findOrderById(order.getId());

                UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
                //添加条件
                wrapper.eq("status",1).set("status",5).eq("id",order.getId());
                //补库存
                itemClient.updateStock(orderDetail.getItemId(),orderDetail.getNum());
                //修改订单信息
                boolean update = orderService.update(wrapper);
                System.out.println("修改订单的状态 "+update);
            }
        }
    }
}
